<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert show-icon center title="添加商品信息" type="info"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 竖行tab栏
      表单区域-->
      <el-form
        ref="addGoodsformRef"
        :model="addGoodsform"
        :rules="addGoodsformRules"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="leaveTagsBefore"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsform.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsform.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsform.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择框 -->
              <el-cascader
                v-model="addGoodsform.goods_cat"
                :options="catList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :label="item2.attr_name"
              v-for="item2 in onlyTableData"
              :key="item2.attr_id"
            >
              <el-input v-model="item2.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addGoodsform.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="handleAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片区域 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img class="previewPic" :src="previewPath" alt />
    </el-dialog>
  </div>
</template>

<script>
// import ParamsVue from './Params.vue'
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      //   添加商品数据
      addGoodsform: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      //   添加商品表单验证规则
      addGoodsformRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入商品分类',
            trigger: 'blur'
          }
        ]
      },
      //   商品列表
      catList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      manyTableData: [],
      onlyTableData: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      picDialogVisible: false
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$msg('获取商品列表数据失败!')
      this.catList = res.data
      console.log(this.catList)
    },
    // 级联选择项变化触发这个函数
    handleChange() {
      if (this.addGoodsform.goods_cat.length !== 3)
        this.addGoodsform.goods_cat = []
      console.log(this.addGoodsform.goods_cat)
    },
    leaveTagsBefore(activeName, oldActiveName) {
      if (this.addGoodsform.goods_cat.length !== 3 && oldActiveName == '0') {
        this.$msg('请选择商品分类')
        return false
      }
    },
    async tabClicked() {
      if (this.activeIndex == '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status != 200) return this.$msg('获取商品分类列表失败')
        // console.log(res)
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else if (this.activeIndex == '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status != 200) return this.$msg('获取静态属性失败')
        console.log(res)
        // debugger
        // res.data.forEach(item => {
        //   item.attr_vals =
        //     item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        // })
        this.onlyTableData = res.data
      }
    },
    // 处理图片逻辑
    handlePreview(file) {
      //   console.log(file)
      this.previewPath = file.response.data.url
      this.picDialogVisible = true
    },
    // 溢出图片时候的逻辑
    handleRemove(file) {
      // 1.获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从pics数组中 找到这个图片对应的索引值
      const i = this.addGoodsform.pics.findIndex(x => x.pic === filePath)
      // 调用数组的splice方法,把图片信息对象从pics中移除
      this.addGoodsform.pics.splice(i, 1)
      console.log(this.addGoodsform)
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // 1.拼接得到一个函数信息对象
      const picsInfo = { pic: response.data.tmp_path }
      // 2.将图片信息对象,push到pics数组中
      this.addGoodsform.pics.push(picsInfo)
      console.log(this.addGoodsform)
    },
    handleAdd() {
      e
      console.log(this.addGoodsform.goods_introduce)
      this.$refs.addGoodsformRef.validate(async valid => {
        if (!valid) return this.$msg('请输入必填数据')

        // 执行添加业务逻辑
        const form = _.cloneDeep(this.addGoodsform)
        form.goods_cat = form.goods_cat.join(',')

        //处理attrs数组，数组中需要包含商品的动态参数和静态属性
        //将manyTableData（动态参数）处理添加到attrs
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        //将onlyTableData（静态属性）处理添加到attrs
        this.onlyTableData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })

        console.log(form)

        //发送请求完成商品的添加,商品名称必须是唯一的
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          console.log(res)
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        //编程式导航跳转到商品列表
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addGoodsform.goods_cat.length == 3)
        return this.addGoodsform.goods_cat[2]
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin-right: 10px;
}
.previewPic {
  width: 100%;
  height: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>